<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2017 河源市卓锐科技有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\member\home;

use app\index\controller\Home;
use app\index\model\GetCityProper as GetCityProperModel;
use app\member\model\Member as MemberModel;
use think\Db;
/**             
 * 登陆控制器
 * @package app\admin\controller
 */
class Login extends Home
{
    //登录页
    public function index()
    {
        $action=$this->request->action();
        $controller=$this->request->controller();
        $map['isdel']=0;
        $map['scenecode']=$controller.'_'.$action;
        $map['status']=1;
        $validation_scene=Db::name('validation_scene')->where($map)->field('id,status')->find();
        if($validation_scene&&$validation_scene['status']==1){
            $check_verify=1;
        }else{
            $check_verify=0;
        }
        $this->assign("check_verify",$check_verify);
        return $this->fetch('login');
    }
    //登录
    public function dologin(){
        if ($this->request->isPost()) {
            $mobile=input('post.mobile');
            $password=input('post.password');
            $autotype=input('post.auto');
            $checkverify=input('post.checkverify');
            $verify=input('post.verify');

            if ($checkverify&&!captcha_check($verify, '', config('captcha'))) {
                return json(['code'=>200,'msg'=>'验证码错误']);
            }
            $status=$this->loginHome($mobile, $password, $autotype);
            if ($status==3) {
                return json(['code'=>200,'msg'=>'登录成功']);
            }elseif($status==0) {
                return json(['code'=>-200,'msg'=>'用户名或密码有误']);
            }elseif($status==1) {
                return json(['code'=>-200,'msg'=>'帐号被禁用,请联系客服']);
            }elseif($status==2) {
                return json(['code'=>-200,'msg'=>'帐号审核不通过,请联系客服']);
            }
        }else{
            return json(['code'=>-200,'msg'=>'请求非法']);
        }
    }
    //注册页
    public function reg(){
        $action=$this->request->action();
        $controller=$this->request->controller();
        $map['isdel']=0;
        $map['scenecode']=$controller.'_'.$action;
        $map['status']=1;
        $validation_scene=Db::name('validation_scene')->where($map)->field('id,status')->find();
        if($validation_scene&&$validation_scene['status']==1){
            $check_verify=1;
        }else{
            $check_verify=0;
        }

        $regoptionbox=Db::name('admin_config')->where('group','regoption')->select();
        $regoption=[];
        foreach ($regoptionbox as $key => $value) {
            # code...
            $regoption[$value['name']] = $value['value'];
        }
        $this->assign('regoption',$regoption);

        $list_province =GetCityProperModel::getProvince();
        $industry=Db::name('member_industry')->where('status=1')->select();//行业
        $company_nature=Db::name('company_nature')->where('status=1')->select();//性质
        $department=Db::name('member_department')->where('status=1')->select();//部门
        
        $this->assign('check_verify',$check_verify);
        $this->assign('industry',$industry);
        $this->assign('department',$department);
        $this->assign('company_nature',$company_nature);
        $this->assign('province',$list_province);
        return $this->fetch();
    }
    /**
     * 会员注册
     * @author yiyouguisu<741459065@qq.com> time|20161111
     * @retrun void
     */
    public function doreg() {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            ($data['is_depot']=='on') ? $data['is_depot']=1 : $data['is_depot']=0;
            unset($data['telverify']);
            unset($data['verify']);
            unset($data['checkverify']);

            $data['provinceid']=$data['province'];
            $provincebox=GetCityProperModel::getPlace(['id'=>$data['province']]);
            $data['province']=$provincebox['name'];

            $data['cityid']=$data['city'];
            $citybox=GetCityProperModel::getPlace(['id'=>$data['city']]);
            $data['city']=$citybox['name'];

            $data['townid']=$data['town'];
            $townbox=GetCityProperModel::getPlace(['id'=>$data['town']]);
            $data['town']=$townbox['name'];

            $mobile=input('post.mobile');
            $password=input('post.password');
        	$telverify=input('post.telverify');
            $checkverify=input('post.checkverify');

            $imgverify=$_POST['verify'];
            if(!empty($data['mobile'])){
                $data['mobile_status']=1;
            }
            if(!empty($data['email'])){
                $data['email_status']=1;
            }
            $regtype='phone';

            $receivertype=0;
            switch ($regtype) {
                case 'phone':
                    # code...
                    $receivertype=0;
                    break;
                case 'email':
                    # code...
                    $receivertype=1;
                    break;
            }
            if ($checkverify&&!captcha_check($_POST['verify'], '', config('captcha'))) {
                return json(['code'=>-200,'msg'=>'验证码错误']);
            }
            $verify=getverify($mobile,0);
            if(strtolower($telverify)!=strtolower($verify)){
                return json(['code'=>-200,'msg'=>'请输入您接收到的正确验证码']);
            }

            if(!check_phone($mobile)&&!empty($mobile)){
                return json(['code'=>-200,'msg'=>'手机号已被注册']);
            }
            // 验证
            $result = $this->validate($data,'Member.reg');
            if(true !== $result) {
                return json(['code'=>-200,'msg'=>$result]);
            }else{
                $data['verify'] = genRandomString(6);
                $pass = MemberModel::encryption($password, $data['verify']);
                $data['password'] = $pass;
                $data['reg_ip']=get_client_ip();
                $id = MemberModel::create($data);
                if ($id) {
                    $this->loginHome($mobile, $password);
                    return json(['code'=>200,'msg'=>'注册成功']);
                } else {
                    return json(['code'=>-200,'msg'=>'注册失败']);
                }
            }
        }else{
            return json(['code'=>-200,'msg'=>'请求非法']);
        }
    }
    /**
     * 忘记密码
     * @author yiyouguisu<741459065@qq.com> time|20161111
     * @retrun void
     */
    public function forgotpassword(){
        if($this->request->isPost()){
            $ret=$_POST;
            $username=input('post.username');
            $new_password=input('post.new_password');

            $where['mobile|email']=$username;
            $user=Db::name('Member')->where($where)->find();
            if(empty($user)) return json(['code'=>-200,'msg'=>'用户不存在']);

            $verify = genRandomString(6);
            $data['verify'] = $verify;
            $data['password'] = MemberModel::encryption($new_password, $verify);
            $id=Db::name('Member')->where("id", $user['id'])->update($data);
            if($id){
                return json(['code'=>200,'msg'=>'重置成功']);
            }else{
                return json(['code'=>-200,'msg'=>'重置失败']);
            }
            
        }else{
            $action=$this->request->action();
            $controller=$this->request->controller();
            $map['isdel']=0;
            $map['scenecode']=$controller.'_'.$action;
            $map['status']=1;
            $validation_scene=Db::name('validation_scene')->where($map)->field('id,status')->find();
            if($validation_scene&&$validation_scene['status']==1){
                $check_verify=1;
            }else{
                $check_verify=0;
            }
            $this->assign('check_verify',$check_verify);
            return $this->fetch();
        }
    }
    /**
     * 验证账号
     * @return void
     * @author yiyouguisu<741459065@qq.com> time|20161111
     */
    public function checkaccout() {
        if($this->request->isPost()){
            $verifyvalue=input('post.verifyvalue');
            
            $telverify=input('post.telverify');
            $imagecode=input('post.verify');
            $checkverify=input('post.checkverify');

            $verify=getverify($verifyvalue,0);
            if(strtolower($telverify)!=strtolower($verify)){
                return json(['code'=>-200,'msg'=>'请输入您接收到的正确验证码']);
            }
            if ($checkverify&&!captcha_check($imagecode, '', config('captcha'))) {
                return json(['code'=>-200,'msg'=>'验证码错误']);
            }

            if(!preg_match("/^1[0-9]{10}$/",$verifyvalue)) return json(['code'=>-200,'msg'=>'验证手机号码格式错误']);

            $where['mobile|email']=$verifyvalue;
            $user=Db::name('Member')->where($where)->find();
            if(empty($user)) return json(['code'=>-200,'msg'=>'用户不存在']);

            return json(['code'=>200,'msg'=>'验证成功']);
            
        } else {
            return json(['code'=>-200,'msg'=>'请求非法']);
        }    
    }

    public function sendchecknum(){
        $verifyvalue=$_POST['verifyvalue'];
        $verifytype=$_POST['verifytype'];
        $tplname=$_POST['tplname'];
        if($verifyvalue==''||$verifytype==''||$tplname==''){
            exit(json_encode(array('code'=>-200,'msg'=>"Request parameter is null!")));
        }else{
            $code=genNumberString(6);
            switch ($verifytype) {
                case 'phone':
                    # code...
                    $phone=$verifyvalue;
                    $verify=Db::name('verify')->where(array('receiver'=>$phone,'type'=>0))->find();
                    if($verify){
                        Db::name('verify')->where(array('receiver'=>$phone,'type'=>0))->update(array(
                            'verify'=>$code,
                            'inputtime'=>time(),
                            'expiretime'=>strtotime("+5 minute"),
                            'status'=>0
                        ));
                    }else{
                        Db::name('verify')->insert(array(
                            'receiver'=>$phone,
                            'verify'=>$code,
                            'inputtime'=>time(),
                            'expiretime'=>strtotime("+5 minute"),
                            'status'=>0,
                            'type'=>0
                        ));
                    }
                    $Sms = controller("Api/Sms",'home');
                    $content=$Sms->getsmstemplate($tplname,array('code'=>$code));
                    $data=json_encode(array('phone'=>$phone,'content'=>$content));
                    $result=$Sms->sendsms($data);
                    if ( 0 == $result['code'] && "OK" == $result['msg']){
                        exit(json_encode(array('code'=>200,'msg'=>"发送成功",'data' => $result)));
                    }else{
                        $data=array('code'=>$code);
                        exit(json_encode(array('code'=>-200,'msg'=>"发送失败",'data' => $data)));
                    }
                    break;
                
                case 'email':
                    # code...
                    $email=$verifyvalue;
                    $verify=Db::name('verify')->where(array('receiver'=>$email,'type'=>1))->find();
                    if($verify){
                        Db::name('verify')->where(array('receiver'=>$email,'type'=>1))->update(array(
                            'verify'=>$code,
                            'inputtime'=>time(),
                            'expiretime'=>strtotime("+5 minute"),
                            'status'=>0
                        ));
                    }else{
                        Db::name('verify')->insert(array(
                            'receiver'=>$email,
                            'verify'=>$code,
                            'inputtime'=>time(),
                            'expiretime'=>strtotime("+5 minute"),
                            'status'=>0,
                            'type'=>1
                        ));
                    }
                    $Email = controller("Api/Email",'home');
                    $content=$Email->getemailtemplate($tplname,array('code'=>$code));
                    $subject=$Email->getemailsubject($tplname."_subject");
                    $data=json_encode(array('email'=>$email,'content'=>$content,'subject'=>$subject));
                    $statuscode=$Email->sendemailapi($data);
                    if($statuscode){
                        $data=array('statuscode'=>$statuscode);
                        exit(json_encode(array('code'=>200,'msg'=>"发送成功",'data' => $data)));
                    }else{
                        $data=array('code'=>$code);
                        exit(json_encode(array('code'=>-200,'msg'=>"发送失败",'data' => $data)));
                    }
                    break;
            }
        }
    }
    
    /**
     * 登陆
     * @param int|string $identifier 用户ID,或者用户名
     * @param string $password 用户密码，不能为空
     * @param int $autotype 是否记住用户自动登录
     * @return int 
     */
    protected function loginHome($identifier, $password, $autotype = 0) {
        if (empty($identifier) || empty($password)) {
            return 0;
        }else{
            $map['status']=1;
            $user = MemberModel::getLocalAdminUser($identifier, $password);
            if (!$user) {
                MemberModel::recordLoginHome($identifier, $password, 0, "帐号密码错误");
                return 0;
            }elseif ($user['is_enable'] == 0) {
                MemberModel::recordLoginHome($identifier, $password, 0, "帐号被禁止");
                return 1;
            }elseif ($user['status'] == 0) {
                MemberModel::recordLoginHome($identifier, $password, 0, "帐号审核未通过");
                return 2;
            }else{
                session('user_name', $user['user_name']);
                session('company', $user['company']);
                session('uid', $user['id']);
                session('puid',$user['parentid']);
                session('mobile', $user['mobile']);
                if ($autotype == 1) {
                    $autoinfo = $user['id'] . "|" . $user['user_name'] . "|" . get_client_ip();
                    $auto = authcode($autoinfo, "ENCODE");
                    cookie('auto', $auto, 7*24*60*60);
                }
                Db::name("member")->where(array("id" => $user['id']))->update(array(
                    "lastlogin_time" => time(),
                    "login_num" => $user["login_num"] + 1,
                    "lastlogin_ip" => get_client_ip()
                ));
                return 3;
            }
        }
        
        
    }
   
}